import {vtdata} from "../../../database/vtdata.js";


export function SearchGroup({idStartDom,idEndDom}){
    this.idStartDom = idStartDom;
    this.idEndDom = idEndDom;
    this.data = null;
}

/**
 * @dataObj {Array<Object>} -数据源
 * @rdObj  {RenderData}  -渲染的实例对象
 * @pgObj  {Pagenator} -分页器的实例对象
 * @toDom   {DomObject}  -数据渲染到什么Dom中
 * @virtualRender {Function} -页面虚拟渲染的回调函数
 * */
SearchGroup.prototype.setSearchOrigin = function({dataObj,rdObj,pgObj,toDom,virtualRender}){
    if(dataObj){
        this.data = dataObj;
    }
    this.rdObj = rdObj;
    this.pgObj = pgObj;
    this.toDom = toDom;
    this.virtualRender = virtualRender;

}

SearchGroup.prototype.search = function(btnDom){

    var _this = this;

    btnDom.addEventListener('click', function(){
        var id = _this.idStartDom.value;
        var _id = _this.idEndDom.value;
        //如果前后两个输入框当中有一个值没有被输入,则两者的值完全相同
        if(id === "" && _id !== ""){
            id = _id;
        }else if(_id === "" && id !== ""){
            _id = id;
        }

        id = parseInt(id);
        _id = parseInt(_id);

        if(Number.isNaN(id) || Number.isNaN(_id)){//true===>NaN
            console.error("输入的id不符合规定!");
            return;
        }

        if(id < 1 || _id < 1){ //id不允许为 0 或 -1及以下
            console.error("输入的id范围过小!");
            return;
        }

        //id输入合法 : 为了写法简单一些,当前采取的策略用 id-1 = index
        var dataObj = []; //新的数据源 查询出来的数据
        for (let i = id; i <= _id ; i++) {
            dataObj.push(_this.data[i-1]);
        }

        if(dataObj.length > 0){
            render(_this,dataObj);
        }
    })
}

SearchGroup.prototype.refresh = function(btnDom){
    var _this = this;

    btnDom.addEventListener('click', function(e){
        render(_this,vtdata);
    })

}

function render(_this,dataObj){
    //重新设置数据量
    _this.pgObj.setPropertys({total:dataObj.length,thePageNum:1});
    _this.pgObj.createPageNumBtn();


    _this.rdObj.virtualRenderDom(_this.virtualRender,_this.toDom,dataObj);
    _this.rdObj.setDataOrigin(dataObj);

    _this.pgObj.clickActive();
    //清空输入框
    _this.idStartDom.value = "";
    _this.idEndDom.value = "";
}